package B刷题.二叉树;

/**
 * @author wei.zhao
 * @description: 剑指 Offer 55 - II.平衡二叉树
 * @date 2022年11月11日 15:20
 */
public class Code07_IsBalanced {

    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        Info info = process(root);
        return info.isB;
    }

    private Info process(TreeNode root) {
        if (root == null) {
            return new Info(true, 0);
        }
        Info lInfo = process(root.left);
        Info rInfo = process(root.right);
        if (lInfo.isB && rInfo.isB && Math.abs(lInfo.level - rInfo.level) < 2) {
            return new Info(true, Math.max(lInfo.level, rInfo.level) + 1);
        }
        return new Info(false, 0);
    }

    public static class Info {
        private boolean isB;
        private Integer level;

        public Info(boolean isB, Integer level) {
            this.isB = isB;
            this.level = level;
        }
    }

}
